import re

from Lib.zcm.exception.TestException import TestException
from Lib.zcm.exception.errortype import ErrorType
from Lib.zcm.fish.Button import Button
from Lib.zcm.common.ui.Selector import Selector
from Lib.zcm.common.ui.Input import Input
from robot.api import logger


class V9ErrorPage(object):

    def __init__(self, driver):
        self._driver = driver

    def is_error_page_exist(self) -> bool:
        if self.dialog_danger.get_element_size() > 0 or self.dialog_warning.get_element_size() > 0:
            return True
        else:
            return False

    def get_exception(self) -> Exception:
        self.detail.click()
        title = self.exception_title.getValue()
        description = self.exception_description.getValue()
        trace_id = ''
        if self.trace_id_span.get_element_size() > 0:
            trace_id_value = self.trace_id_span.getValue()
            logger.debug("Exception trace id ={0}".format(trace_id_value))
            # [172016025157_18412_1^1598324029115^51][copy]  172016025157_18412_1^1598324029115^51
            trace_id = trace_id_value.split('][')[0].split('[')[1] if trace_id_value else ''
        logger.error("Exception occurred! Details are as follows.\n{0}\nDescription: {1}\nTraceId: {2}\n".format(
            title, description, trace_id))

        # V9的业务报错直接放在第一层，不再对异常封装
        # Modified by james at 20200817
        code = title.split(":")[-1].strip()  # Code[40338202]
        matches = re.findall(r'Code\[(\d*)\]', code)
        error_code = matches[0] if len(matches) > 0 else code

        return TestException(msg=description, err_code=error_code, err_class=ErrorType.BUSINESS, portal_version='V9',
                             trace_id=trace_id)
        # e = TestException(portal_version='V9', trace_id=trace_id, busi_err_code=title.split(":")[1],
        #                   busi_msg=description)
        # return TestException.by_error_code(ErrorCode.BUSINESS_FLOW_ERROR, e)

    @property
    def warming_ok(self):
        return Button(self._driver, "button[class='btn btn-warning js-close']", Selector.CSS_SELECTOR)

    @property
    def detail(self):
        return Button(self._driver, "button[class='btn btn-default js-stack']", Selector.CSS_SELECTOR)

    @property
    def error_ok(self):
        return Button(self._driver, "button[class='btn btn-danger js-close']", Selector.CSS_SELECTOR)

    @property
    def exception_title(self):
        return Input(self._driver, "span[class='modal-title']", Selector.CSS_SELECTOR)

    @property
    def dialog_danger(self):
        return Input(self._driver, "dialog-danger")

    @property
    def dialog_warning(self):
        return Input(self._driver, "dialog-warning")

    @property
    def exception_description(self):
        return Input(self._driver, "//div[@class='modal-body']/h3", Selector.XPATH)

    @property
    def trace_id_span(self):
        return Input(self._driver, "span[class='trace']", Selector.CSS_SELECTOR)
